<template>
  <view class="comments_page">
    <uni-nav-bar 
      @clickLeft="goBack" 
      left-icon="back" 
      leftIcon="arrowleft" 
      title="店铺评价" 
      statusBar="true" 
      fixed="true"
      color="#ffffff" 
      backgroundColor="#333333">
    </uni-nav-bar>

    <!-- 店铺总体评价 -->
    <view class="shop-score-summary">
      <view class="score-box">
        <text class="score">{{ shopScore.toFixed(1) }}</text>
        <text class="score-label">总体评分</text>
      </view>
      <text class="good-rate">好评率 {{ goodCommentRate }}%</text>
    </view>

    <!-- 评价分类滚动栏 -->
    <scroll-view 
      scroll-x 
      class="scroll-row" 
      :scroll-into-view="scrollinto" 
      :scroll-with-animation="true" 
      enable-flex>
      <view 
        v-for="(item, index) in tabBars" 
        :key="index" 
        :id="'tab' + index" 
        class="scroll-row-item"
        @click="changeTab(index)">
        <view :class="tabIndex == index ? 'scroll-row-item-act' : ''">
          <text class="line"></text>{{ item }}
        </view>
      </view>
    </scroll-view>

    <!-- 评价列表 -->
    <swiper 
      :current="tabIndex" 
      @change="onChangeSwiperTab" 
      :style="{ height: scrollH + 'px' }">
      <swiper-item v-for="(item, index) in tabBars" :key="index">
        <scroll-view 
          scroll-y 
          :style="{ height: scrollH + 'px' }" 
          @scrolltolower="lower">
          <view class="main comments_list" v-if="commentsList && commentsList.length > 0">
            <view 
              class="box comment_item" 
              v-for="(comment, index) in commentsList" 
              :key="index" 
              :class="{
                'item-last': Number(index) + 1 === commentsList.length,
              }">
              <!-- 原始评论 -->
              <view class="comment-main" @click="goToCommentDetail(comment)">
                <image :src="comment.userAvatar" class="user-avatar"></image>
                <view class="comment-content-wrapper">
                  <view class="comment-user-info">
                    <text class="username">{{ comment.userName }}</text>
                    <text class="comment-time">{{ comment.createTime }}</text>
                  </view>
                  <text class="comment-text">{{ comment.content }}</text>
                  
                  <!-- 评论图片 -->
                  <view class="comment-images" v-if="comment.images && comment.images.length">
                    <image 
                      v-for="(img, imgIdx) in comment.images" 
                      :key="imgIdx" 
                      :src="img" 
                      mode="aspectFill"
                      class="comment-image">
                    </image>
                  </view>
                  
                  <!-- 回复按钮和回复数 -->
                  <view class="comment-interaction">
                    <view 
                      class="reply-trigger" 
                      @click.stop.prevent="handleReplyClick(comment)">
                      <text>回复</text>
                      <text 
                        v-if="comment.replies && comment.replies.length" 
                        class="reply-count">
                        {{ comment.replies.length }}
                      </text>
                    </view>
                  </view>
                </view>
              </view>
              
              <!-- 行内回复输入框 -->
              <view 
                v-if="currentReplyComment === comment && showReplyInput" 
                class="inline-reply-container"
              >
                <textarea 
                  v-model="replyContent"
                  placeholder="说点什么..."
                  class="inline-reply-textarea"
                  maxlength="200"
                ></textarea>
                <view class="inline-reply-footer">
                  <text class="text-count">{{ replyContent.length }}/200</text>
                  <view 
                    class="submit-btn" 
                    @click.stop.prevent="submitInlineReply"
                  >
                    发送
                  </view>
                </view>
              </view>
              
              <!-- 回复列表 -->
              <view 
                class="replies-container" 
                v-if="comment.replies && comment.replies.length">
                <view 
                  class="reply-item" 
                  v-for="(reply, replyIdx) in comment.replies" 
                  :key="replyIdx">
                  <view class="reply-content">
                    <text class="reply-username">{{ reply.userName }}：</text>
                    <text class="reply-text">{{ reply.content }}</text>
                  </view>
                  <view 
                    class="reply-interaction"
                    @click="handleReplyClick(comment, reply)">
                    <text>回复</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="empty-tips" v-else>
            <text>暂无评价</text>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
    
    <!-- 回复弹窗 -->
    <uni-popup ref="replyPopup" type="bottom">
      <view class="reply-popup">
        <view class="reply-header">
          <text class="reply-title">
            {{ replyTarget ? `回复 ${replyTarget.userName}` : '发表评论' }}
          </text>
        </view>
        <textarea 
          v-model="replyContent" 
          placeholder="说点什么..." 
          class="reply-textarea"
          maxlength="200">
        </textarea>
        <view class="reply-footer">
          <text class="text-count">{{ replyContent.length }}/200</text>
          <button 
            @click="submitReply" 
            class="submit-btn" 
            :disabled="!replyContent.trim()">
            发送
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getComments, addCommentReply, getCommentReplies } from "../api/api.js";

export default {
  data() {
    return {
      commentsList: [],
      pageInfo: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      commentType: "",
      loadingType: 0,
      showTitle: false,
      scrollinto: "tab0",
      scrollH: 0,
      tabIndex: 0,
      tabBars: ["全部评价", "好评", "差评", "置顶"],
      urlMap: {
        0: {
    fn: (params) => getComments(params),
    key: "type",
  },
  1: {
    fn: (params) => getComments(params),
    key: "type",
  },
  2: {
    fn: (params) => getComments(params),
    key: "type",
  },
  3: {
    fn: (params) => getComments(params),
    key: "type",
  }
       
      },
      shopScore: 4.8,
      goodCommentRate: 95,
      isEmpty: false,
      currentComment: null,
      replyContent: '',
      replyTarget: null,
      showReplyInput: false,
      currentReplyComment: null,
    };
  },
  onLoad() {
    this.getList();
  },
  onUnload() {
    this.showTitle = false;
  },
  onReady() {
    uni.getSystemInfo({
      success: (res) => {
        this.scrollH = res.windowHeight - uni.upx2px(100);
      },
    });
  },
  onPullDownRefresh() {
    this.pageInfo.page = 1;
    this.loadingType = 0;
    this.commentsList = [];
    this.getList();
    uni.stopPullDownRefresh();
    this.showTitle = true;
  },
  onReachBottom() {
    if (this.commentsList.length < Number(this.pageInfo.total)) {
      this.pageInfo.page++;
      this.loadingStatus = "loading";
      this.getList();
      this.showTitle = true;
    }
  },
  methods: {
    getList() {
      const key = this.urlMap[this.tabIndex].key;
      const fn = this.urlMap[this.tabIndex].fn;
      const params = {
        pageSize: 10,
        page: this.pageInfo.page,
      };
      
      if (this.tabIndex === 0) {
        // 全部评价不需要额外参数
      } else if (this.tabIndex === 1) {
        params.type = "1";  // 好评
      } else if (this.tabIndex === 2) {
        params.type = "2";  // 差评
      } else if (this.tabIndex === 3) {
        params.status = "1";  // 置顶
      }
      
      uni.showLoading({ title: "加载中", mask: true });
      fn(params).then((res) => {
        if (res.code === 1) {
          setTimeout(function () {
            uni.hideLoading();
          }, 100);
          
          // 如果是置顶页面，额外过滤 status=1 的评论
          if (this.tabIndex === 3) {
            res.data.records = res.data.records.filter(record => record.status === 1);
          }
          
          console.group('评论列表调试')
          console.log('返回的评论数据:', res.data.records)
          console.log('第一条评论的用户信息:', res.data.records[0])
          console.groupEnd()

          this.commentsList = this.commentsList.concat(res.data.records);
          this.pageInfo.total = res.data.total;
          this.isEmpty = true;
        }
      });
    },
    changeTab(index) {
      if (this.tabIndex == index) {
        return;
      }
      this.tabIndex = index;
      
      this.pageInfo.page = 1;
      this.commentsList = [];
      this.getList();
      this.scrollinto = "tab" + index;
    },
    onChangeSwiperTab(e) {
      this.changeTab(e.detail.current);
    },
    lower() {
      if (this.commentsList.length < Number(this.pageInfo.total)) {
        this.pageInfo.page++;
        this.loadingStatus = "loading";
        this.getList();
      }
    },
    goBack() {
      uni.navigateBack();
    },
    showReplyPopup(comment, replyTarget = null) {
      this.currentReplyComment = comment;
      this.replyTarget = replyTarget;
      this.replyContent = '';
      this.$refs.replyPopup.open();
    },
    submitInlineReply() {
      console.group('回复调试信息')
      console.log('当前评论对象:', this.currentReplyComment)
      console.log('回复目标对象:', this.replyTarget)
      
      if (!this.currentReplyComment || !this.currentReplyComment.id) {
        uni.showToast({
          title: '请选择要回复的评论',
          icon: 'none'
        });
        console.warn('缺少当前评论对象')
        console.groupEnd()
        return;
      }

      if (!this.replyContent.trim()) {
        uni.showToast({
          title: '回复内容不能为空',
          icon: 'none'
        });
        console.warn('回复内容为空')
        console.groupEnd()
        return;
      }
      
      // 获取当前登录用户信息
      const userInfo = uni.getStorageSync('userInfo')
      const currentUsername = userInfo ? userInfo.nickName : '匿名用户'
      
      const params = {
        // 使用目标评论的 id 作为 rootId
        rootId: this.currentReplyComment.id,
        
        // 使用目标评论的用户名作为 rootName
        rootName: this.currentReplyComment.userName || this.currentReplyComment.username || '匿名用户',
        
        // 使用当前评论的 userName 作为 parentName
        parentName: this.currentReplyComment.userName || '匿名用户',
        
        // 当前用户名
        userName: currentUsername,
        
        // 回复的内容
        content: this.replyContent.trim(),
      }

      console.log('构建的请求参数:', params)
      console.groupEnd()
      
      addCommentReply(params).then(res => {
        console.log('回复接口返回:', res)
        
        if (res.code === 1) {
          uni.showToast({
            title: '回复成功',
            icon: 'success',
            duration: 1500
          });
          
          // 重置回复相关状态
          this.replyContent = '';
          this.showReplyInput = false;
          this.currentReplyComment = null;
          this.replyTarget = null;
          
          // 关闭回复弹窗
          if (this.$refs.replyPopup) {
            this.$refs.replyPopup.close()
          }
          
          // 重新加载评论列表
          this.pageInfo.page = 1;
          this.commentsList = [];
          this.getList();
        } else {
          uni.showToast({
            title: res.msg || '回复失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('回复失败:', err)
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      });
    },
    fetchCommentReplies(commentId) {
      getCommentReplies({ commentId }).then(res => {
        if (res.code === 1) {
          const commentIndex = this.commentsList.findIndex(
            comment => comment.id === commentId
          );
          
          if (commentIndex !== -1) {
            this.$set(
              this.commentsList[commentIndex], 
              'replies', 
              res.data.records
            );
          }
        }
      });
    },
    goToCommentDetail(comment) {
      console.log('准备跳转到评论详情页，当前评论:', comment)
      
      // 将完整的评论对象转换为 JSON 字符串传递
      const commentStr = encodeURIComponent(JSON.stringify(comment))
      
      // 使用评论的 id 和完整评论对象作为跳转参数
      uni.navigateTo({
        url: `/pages/comments/detail?commentId=${comment.id}&comment=${commentStr}`,
        success: (res) => {
          console.log('跳转成功', res)
        },
        fail: (err) => {
          console.error('跳转失败', err)
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          })
        }
      });
    },
    handleReplyClick(comment, replyTarget = null) {
      // 如果是在移动端或小屏幕，使用弹窗
      uni.getSystemInfo({
        success: (res) => {
          if (res.windowWidth < 768) {
            // 使用原有的弹窗方法
            this.showReplyPopup(comment, replyTarget)
          } else {
            // 大屏幕使用行内回复
            if (this.currentReplyComment === comment) {
              this.showReplyInput = !this.showReplyInput
            } else {
              // 否则显示新评论的回复框
              this.currentReplyComment = comment
              this.replyTarget = replyTarget
              this.showReplyInput = true
            }
          }
        },
        fail: () => {
          // 如果获取系统信息失败，默认使用弹窗
          this.showReplyPopup(comment, replyTarget)
        }
      })
    },
    submitReply() {
      // 直接调用 submitInlineReply
      this.submitInlineReply();
    },
  }
};
</script>

<style lang="scss" scoped>
.comments_page {
  height: 100%;
}

.shop-score-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
}

.score-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.score {
  font-size: 72rpx;
  color: #ffc200;
  font-weight: bold;
}

.score-label {
  font-size: 24rpx;
  color: #666;
}

.good-rate {
  color: #666;
  font-size: 28rpx;
}

.scroll-row {
  height: 88rpx;
  line-height: 88rpx;
  background-color: #fff;
  padding: 0 30rpx;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.06);
  width: 100vw;
  box-sizing: border-box;
  flex-wrap: nowrap;
  overflow: auto;
  display: flex;
}

.scroll-row-item {
  margin-right: 88rpx;
  color: #666;
  display: inline-block;
  font-size: 28rpx;
  flex-shrink: 0;
}

.scroll-row-item-act {
  color: #333;
  position: relative;
  font-weight: 600;
}

.scroll-row-item-act .line {
  width: 32rpx;
  height: 8rpx;
  display: block;
  background: #ffc200;
  border-radius: 8rpx;
  transform: translate(-50%, -50%);
  position: absolute;
  bottom: -4rpx;
  left: 50%;
}

.comment_item {
  display: flex;
  flex-direction: column;
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 12rpx;
}

.comment-main {
  display: flex;
  align-items: flex-start;
}

.user-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.comment-content-wrapper {
  flex: 1;
}

.comment-user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.username {
  font-weight: bold;
  color: #333;
  font-size: 28rpx;
}

.comment-time {
  color: #999;
  font-size: 24rpx;
}

.comment-text {
  color: #333;
  font-size: 30rpx;
  line-height: 1.5;
}

.comment-images {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.comment-image {
  width: 200rpx;
  height: 200rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  border-radius: 8rpx;
}

.comment-interaction {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 10rpx;
}

.reply-trigger {
  display: inline-flex;
  align-items: center;
  color: #666;
  font-size: 24rpx;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  cursor: pointer;
}

.reply-trigger text {
  margin-right: 5rpx;
}

.reply-count {
  background-color: #e0e0e0;
  border-radius: 16rpx;
  padding: 0 8rpx;
  font-size: 20rpx;
  min-width: 20rpx;
  text-align: center;
}

.replies-container {
  margin-top: 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 10rpx;
}

.reply-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #e0e0e0;
}

.reply-content {
  flex: 1;
}

.reply-username {
  color: #666;
  font-weight: bold;
  margin-right: 10rpx;
  font-size: 26rpx;
}

.reply-text {
  color: #333;
  font-size: 26rpx;
}

.replies-container .reply-interaction {
  display: inline-flex;
  align-items: center;
  color: #666;
  font-size: 24rpx;
  background-color: #f5f5f5;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  cursor: pointer;
  margin-left: 10rpx;
}

.reply-popup {
  background-color: white;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding: 20rpx;
}

.reply-header {
  text-align: center;
  margin-bottom: 20rpx;
}

.reply-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.reply-textarea {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20rpx;
}

.text-count {
  color: #999;
  font-size: 24rpx;
}

.submit-btn {
  background-color: #ffc200;
  color: white;
  padding: 10rpx 30rpx;
  border-radius: 50rpx;
}

.submit-btn:disabled {
  background-color: #e0e0e0;
  color: #999;
}

.inline-reply-container {
  background-color: #f5f5f5;
  border-radius: 10rpx;
  padding: 20rpx;
  margin-top: 10rpx;
}

.inline-reply-textarea {
  width: 100%;
  min-height: 200rpx;
  background-color: white;
  border-radius: 10rpx;
  padding: 10rpx;
  margin-bottom: 10rpx;
}

.inline-reply-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.inline-reply-footer .text-count {
  color: #999;
  font-size: 24rpx;
}

.inline-reply-footer .submit-btn {
  background-color: #007bff;
  color: white;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
}

.empty-tips {
  text-align: center;
  color: #999;
  padding: 50rpx 0;
}
</style>